package com.ubxtech.cloud.filter;

import com.ubxtech.core.context.ContextConstants;
import com.ubxtech.core.context.ContextUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.GenericFilterBean;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 * @author Victor.Xiao
 * @since 2023-08-22 19:43
 **/
@Slf4j
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class VersionContextHolderFilter extends GenericFilterBean {

    @Override
    @SneakyThrows
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String version = request.getHeader(ContextConstants.HEADER_GRAY_VERSION_NAME);
        if (log.isDebugEnabled() && StringUtils.hasText(version)) {
            log.debug("获取header中的VERSION为:{}", version);
        }
        ContextUtil.setGrayVersion(version);
        filterChain.doFilter(request, response);
        ContextUtil.remove(ContextConstants.HEADER_GRAY_VERSION_NAME);
    }
}
